package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.HttpClientUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPartFeignService;
import com.atguigu.gulimall.auth.utils.ConstantPropertiesUtil;
import com.atguigu.common.vo.MemberResVo;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import com.google.gson.Gson;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@CrossOrigin
@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MemberFeignService memberFeignService;


    @GetMapping("/sms/sendcode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone){

        //TODO 防止接口重刷
        String redisCode = stringRedisTemplate.opsForValue().get(AuthConstant.AUTH_CODE_PRFIX + phone);

        if(StringUtils.isNotEmpty(redisCode)){
            Long l = Long.parseLong(redisCode.substring(5));
            if(System.currentTimeMillis()-l<60000){
                //60秒内不能重复发送
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());

            }
        }

        String code = RandomStringUtils.randomNumeric(5);
        String checkCode = code+"_" +System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set(AuthConstant.AUTH_CODE_PRFIX+phone,checkCode,3, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone,code);

        return R.ok();
    }


    @PostMapping("/regist")
    public  String regist(@Valid UserRegistVo userRegistVo, BindingResult bindingResult,
                          RedirectAttributes redirectAttributes){

        if(bindingResult.hasErrors()){
            Map<String, String> errors = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(fieldError -> fieldError.getField(), fieldError -> fieldError.getDefaultMessage()));
            redirectAttributes.addFlashAttribute("errors",errors);

            //防止表单重复提交  重定向而不是转发
            return "redirect:http://auth.gulimall.com/reg.html";
        }


        //校验验证码
        String checkcode = userRegistVo.getCode();
        String s = stringRedisTemplate.opsForValue().get(AuthConstant.AUTH_CODE_PRFIX + userRegistVo.getPhone()).substring(0,5);
        if(StringUtils.isNotEmpty(s)){
            if(s.equals(checkcode)){
                //验证码判断成功
                //删除验证码
                stringRedisTemplate.delete(AuthConstant.AUTH_CODE_PRFIX+userRegistVo.getPhone());

                //验证码通过  //真正注册
                R r = memberFeignService.regist(userRegistVo);
                if(r.getCode()==0){
                    //注册成功


                    return "redirect:http://auth.gulimall.com/login.html";

                }else{
                    Map<String,String> errors = new HashMap<>();
                    errors.put("msg",r.getMsg());
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth:gulimall.com/reg.html";
                }
            }else{
                //验证码错误
                Map<String,String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth:gulimall.com/reg.html";
            }

        }else{
            //验证码过时
            Map<String,String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth:gulimall.com/reg.html";
        }
        //调用远程服务 进行注册


    }

    //手机号登录
    @PostMapping("/login")
    public String login(UserLoginVo loginVo,RedirectAttributes redirectAttributes,HttpSession session){


        R r = memberFeignService.login(loginVo);
        if(r.getCode()==0){
            String member = JSON.toJSONString(r.get("member"));
            MemberResVo res = JSON.parseObject(member, MemberResVo.class);
            session.setAttribute("loginUser",res);

            return "redirect:http://gulimall.com/";
        }else{
           Map<String,String> map = new HashMap<>();
           map.put("msg",r.getMsg());

           redirectAttributes.addFlashAttribute("errors",map);
            return "redirect:http://auth.gulimall.com/login.html";
        }


    }


    //获取微信验证码
    @GetMapping("/auth/weixin/getWeixinCode")
    public String getWeixinCode(){

// 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        // 回调地址
//        String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
//        try {
//            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
//        } catch (UnsupportedEncodingException e) {
//            throw new GuliException(20001, e.getMessage());
//        }
        // 防止csrf攻击（跨站请求伪造攻击）
        //String state = UUID.randomUUID().toString().replaceAll("-", "");//一般情况下会使用一个随机数
//        String state = "imhelen";//为了让大家能够使用我搭建的外网的微信回调跳转服务器，这里填写你在ngrok的前置域名
//        System.out.println("state = " + state);
        // 采用redis等进行缓存state 使用sessionId为key 30分钟后过期，可配置
        //键："wechar-open-state-" + httpServletRequest.getSession().getId()
        //值：satte
        //过期时间：30分钟

      String redirectUrl =  ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
      try{

     redirectUrl = URLEncoder.encode(redirectUrl,"utf-8");

      }catch (Exception e){

      }
        //生成qrcodeUrl
        String qrcodeUrl = String.format(
                baseUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                redirectUrl,
                "gulimall");


        return "redirect:" + qrcodeUrl;


    }

    //扫码成功后，直接请求这个方法，处理我们信息，
    //http://localhost:8160/api/ucenter/wx/callback?code=021zqNFa1PjzIB0mD0Ja1O4ru01zqNFJ&state=gulimall

   @GetMapping("/api/ucenter/wx/callback")
    public String callback(@RequestParam("code") String code, @RequestParam("state") String state
    , HttpSession session){
        //请求access_token：访问凭证
    //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code


//从redis中将state获取出来，和当前传入的state作比较
//如果一致则放行，如果不一致则抛出异常：非法访问
//向认证服务器发送请求换取access_token
        String baseAccessTokenUrl =
                "https://api.weixin.qq.com/sns/oauth2/access_token" +
                        "?appid=%s" +
                        "&secret=%s" +
                        "&code=%s" +
                        "&grant_type=authorization_code";
        String accessTokenUrl = String.format(baseAccessTokenUrl,
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);
        String result = null;
        try {
            result = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessToken=============" + result);
        } catch (Exception e) {
           e.printStackTrace();
        }
//解析json字符串
        Gson gson = new Gson();
        HashMap map = gson.fromJson(result, HashMap.class);
        String accessToken = (String)map.get("access_token");
        String openid = (String)map.get("openid");

        R r = memberFeignService.openId(openid);
        if(r.getCode()==0){
            //用户存在

            String member = JSON.toJSONString(r.get("member"));
            MemberResVo res = JSON.parseObject(member, MemberResVo.class);
           session.setAttribute("user",res);
            System.out.println("user:-----"+session.getAttribute("user"));


        }else{
            //访问微信的资源服务器，获取用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
            String resultUserInfo = null;
            //查询用户信息
            try {
                resultUserInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("resultUserInfo==========" + resultUserInfo);
            } catch (Exception e) {
                e.printStackTrace();

            }
                //解析json
                HashMap<String, Object> mapUserInfo = gson.fromJson(resultUserInfo,
                        HashMap.class);
                String nickname = (String)mapUserInfo.get("nickname");
                String headimgurl = (String)mapUserInfo.get("headimgurl");

            MemberResVo memberResVo = new MemberResVo();
            memberResVo.setHeader(headimgurl);
            memberResVo.setNickname(nickname);
            memberResVo.setOpenId(openid);

            R save = memberFeignService.save(memberResVo);
            if(save.getCode()==0) {
                //注册成功
               session.setAttribute("user", memberResVo);
                System.out.println(memberResVo);
            }


        }

        return "redirect:http://gulimall.com";


    }


    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object loginUser = session.getAttribute("loginUser");

        if(loginUser==null){
            return "login";
        }else{
            return "redirect:http://gulimall.com";
        }
    }
}
